import { useState } from 'react'
import { Table, Card, Form, Select, DatePicker, Button, Space, Tag } from 'antd'
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons'
import { useQuery } from '@tanstack/react-query'
import { getLogs } from '../api/gateway'
import dayjs from 'dayjs'

const { RangePicker } = DatePicker

export default function Logs() {
  const [form] = Form.useForm()
  const [params, setParams] = useState<any>({
    page: 1,
    pageSize: 20,
  })

  const { data, isLoading } = useQuery({
    queryKey: ['logs', params],
    queryFn: () => getLogs(params),
    refetchInterval: 5000,
  })

  const handleSearch = () => {
    const values = form.getFieldsValue()
    setParams({
      ...params,
      ...values,
      page: 1,
    })
  }

  const handleReset = () => {
    form.resetFields()
    setParams({ page: 1, pageSize: 20 })
  }

  const columns = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      render: (level: string) => {
        const colorMap: any = {
          error: 'red',
          warn: 'orange',
          info: 'blue',
          debug: 'default',
        }
        return <Tag color={colorMap[level] || 'default'}>{level}</Tag>
      },
    },
    {
      title: '路由',
      dataIndex: 'route',
      key: 'route',
    },
    {
      title: '方法',
      dataIndex: 'method',
      key: 'method',
    },
    {
      title: '路径',
      dataIndex: 'path',
      key: 'path',
    },
    {
      title: 'IP',
      dataIndex: 'client_ip',
      key: 'client_ip',
    },
    {
      title: '状态码',
      dataIndex: 'status_code',
      key: 'status_code',
      render: (code: number) => {
        const color = code >= 400 ? 'red' : code >= 300 ? 'orange' : 'green'
        return <Tag color={color}>{code}</Tag>
      },
    },
    {
      title: '用户',
      dataIndex: 'username',
      key: 'username',
    },
  ]

  return (
    <div>
      <h1 style={{ marginBottom: '24px' }}>日志查看</h1>
      <Card style={{ marginBottom: '16px' }}>
        <Form form={form} layout="inline">
          <Form.Item name="level" label="日志级别">
            <Select style={{ width: 120 }} allowClear>
              <Select.Option value="debug">DEBUG</Select.Option>
              <Select.Option value="info">INFO</Select.Option>
              <Select.Option value="warn">WARN</Select.Option>
              <Select.Option value="error">ERROR</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="timeRange" label="时间范围">
            <RangePicker showTime />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button
                type="primary"
                icon={<SearchOutlined />}
                onClick={handleSearch}
              >
                查询
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Table
        columns={columns}
        dataSource={data?.list || []}
        loading={isLoading}
        rowKey="id"
        pagination={{
          current: params.page,
          pageSize: params.pageSize,
          total: data?.total || 0,
          onChange: (page, pageSize) => {
            setParams({ ...params, page, pageSize })
          },
        }}
      />
    </div>
  )
}

